require('./db/initdb');
const { publicPath, mongoUrl } = require('./serverOpt');
const createError = require('http-errors');
const express = require('express'); //ws相关
const expressWs = require('express-ws');
const logger = require('morgan');
const app = express();
expressWs(app); //ws相关
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });
app.use(bodyParser.json({ limit: '100mb' ,parameterLimit: 100000 }));
app.use(bodyParser.urlencoded({ limit: '100mb', parameterLimit: 100000 ,extended: true }));
const session = require('express-session');
const MongoStore = require('connect-mongo');
// 首先处理静态文件
app.get('/favicon.ico', (req, res) => res.status(204).end());
app.use(express.static(publicPath));
// 添加全局CORS处理
app.use(cors({
  origin: '*', // 开发环境用通配符
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
// 配置视图引擎
app.set('view engine', 'ejs');
app.set('views', './views');

// 配置中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


//脚本更新相关
const jbGengXin = require('./routes/jbGengXin');
const jbUpFile = require('./routes/jbUpFile');

app.use('/', jbGengXin);
app.use('/', jbUpFile);

//云控ws相关
var { router: wsRouter } = require('./routes/wsRouter');
app.use('/wsRouter', wsRouter);

// app.use(cookieParser());
app.use(
	session({
		resave: true, //resave是指每次请求都重新设置session cookie，假设你的cookie是10分钟过期，每次请求都会再设置10分钟
		secret: 'jinZhu',
		saveUninitialized: false, //saveUninitialized是指无论有没有session cookie，每次请求都设置个session cookie ，默认给个标示为 connect.sid
		// cookie: { expires: false },//这里确保了session cookie在浏览器关闭时会过期
		store: new MongoStore({
			mongoUrl: mongoUrl,
			ttl: 7 * 24 * 60 * 60,
			// ttl: 10 * 60
		}),
	}),
);

// 配置路由
const indexRouter = require('./routes/index');
const user = require('./routes/user');
const ecjbUpFile = require('./routes/ECjbUpFile');
//云控分组设备相关
var indexDevice = require('./routes/indexDevice');
var indexGroup = require('./routes/indexGroup');

var dict = require('./routes/dict');
app.use('/dict', dict);

// 订单和余额记录路由
var order = require('./routes/order');
var orderDetail = require('./routes/orderDetail');
var qqLogin = require('./routes/qqLogin');
app.use('/order', order);
app.use('/order-detail', orderDetail);
app.use('/', qqLogin);
var balanceRecord = require('./routes/balanceRecord');
app.use('/balanceRecord', balanceRecord);

app.use('/ecjbUpFile', ecjbUpFile);
app.use('/indexDevice', indexDevice);
app.use('/indexGroup', indexGroup);

//用户登录相关
app.use('/', indexRouter);
app.use('/user', user);


// 捕捉 404 错误，并转发到错误处理器
app.use(function (req, res, next) {
	next(createError(404, '未找到页面或内容'));
});

// 错误处理
app.use(function (err, req, res, next) {
	const errMsg = err.message;
	if (errMsg == '未找到页面或内容') {
		console.error(`${errMsg}:${req.url}`);
	} else {
		console.error(`node未处理的错误:${req.url}`, err);
	}
	res.status(err.status || 500).json({
		code: err.status || 500,
		message: errMsg,
	});
});




module.exports = app;
